package com.lagou.edu.reader;

import com.lagou.edu.factory.BeanFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class BeanReader {

    private static List<Class<?>> classes = new ArrayList<>();

    public static List<Class<?>> reader(String configPath) throws DocumentException, ClassNotFoundException {
        InputStream resourceAsStream = BeanFactory.class.getClassLoader().getResourceAsStream(configPath);
        // 解析xml
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(resourceAsStream);
        Element rootElement = document.getRootElement();
//        List<Element> beanList = rootElement.selectNodes("//bean");
        //注解扫描的路径
        List<Element> annoList = rootElement.selectNodes("//context");
        Element element1 = annoList.get(0);
        //获取需要扫描的包
        String value = element1.attributeValue("base-package");
        doScanner(value);
//        List<Class<?>> classes1 = doScanner(value);
        return classes;
    }

    public static void doScanner(String packagePath) throws ClassNotFoundException {

//        URL url = this.getClass().getClassLoader().getResource( packagePath.replaceAll("\\.", "/"));
        URL url = BeanReader.class.getResource("/"+ packagePath.replaceAll("\\.", "/"));
//        URL url = this.getClass().getClassLoader().getResource("/");
        File classPath = new File(url.getFile());
        for (File file : classPath.listFiles()) {
            if (file.isDirectory()) {
                doScanner(packagePath + "." + file.getName());
            } else {
                if (!file.getName().endsWith(".class")) {
                    continue;
                }
                String className = (packagePath + "." + file.getName().replace(".class", ""));
                Class<?> aClass = Class.forName(className);
                classes.add(aClass);
            }
        }

    }
}
